#include "bst_tree.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN_MAX 512

char buffer[LEN_MAX];

// action 函数
bool printStr(void *str) {
  if (*(char *)str != '\n')
    return printf("%s", (char *)str) >= 0;
  return false;
}

int main() {
  btree tree = bst_create((cmp_func_t *)strcmp, NULL);

  // 修改成你自己的路径
  FILE *fp = fopen(
      "D:/git/c-general-data-structure/tree/bst_tree_level_order/text", "r");

  if (fp == NULL) {
    fprintf(stderr, "error open file \n");
    exit(EXIT_FAILURE);
  }

  while (fgets(buffer, LEN_MAX, fp) != NULL) { // 读取每一行
    size_t len = strlen(buffer);
    if (!bst_insert(tree, buffer, len + 1)) // 将文本数据复制到树结构中
      break;
  }

  if (!feof(fp)) {
    fprintf(stderr, "sortlines: Error reading or storing text input.\n");
    exit(EXIT_FAILURE);
  }
  int n = bst_in_order(tree, printStr); // LNR输出, 也就是按字符排序
  fprintf(stderr, "sortlines in order: Printed %d lines.\n", n);

  printf("\n");

  n = bst_level_order(tree, printStr); // 按层序输出
  fprintf(stderr, "sortlines level order: Printed %d lines.\n", n);

  printf("\n");

  bst_delete(tree, "e\n"); // 书中的数据行多存了一个换行符

  n = bst_level_order(tree, printStr); // 按层序输出
  fprintf(stderr, "sortlines: level Printed %d lines.\n", n);

  bst_clear(tree);
  fclose(fp);
  return 0;
}

//                 e
//             ╱      ╲
//            a        f
//            ╲         ╲
//             d         g
//            ╱           ╲
//          c              h
//         ╱
//        b
// 中序: a b c d e f g
// 层序: e a f d g c h b